<template>
  <div class="input_home">
    <input type="text" placeholder="请输入查找内容" v-model="search" />
  </div>

  <el-radio-group v-model="activeTag" size="small" class="tag-group">
    <el-radio-button 
      v-for="tag in tags" 
      :key="tag" 
      :label="tag"
    >
      {{ tag }}
    </el-radio-button>
  </el-radio-group>

  <div class="content-list">
    <el-card 
      v-for="item in filteredArticles" 
      :key="item.id" 
      shadow="hover"
      class="article-card"
      @click="goToArticlePage(item.id)"
    >
      <template #header>
        <div class="card-header">
          <h3>{{ item.title }}</h3>
        </div>
      </template>
      <div class="article-content">
        {{ item.content }}
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useTagCenter } from '@/stores/tagCenter';
import { useArticlesStore } from '@/stores/articles';

const TagCenter = useTagCenter();
const router = useRouter();
const articleStor = useArticlesStore();

const activeTag = ref('全部');
const tags = ref<string[]>(['全部']);
const search = ref('');

interface User {
  id: number;
  title: string;
  content: string;
  userid: number;
  username: string;
  tags: string[];
}

const articles = ref<User[]>([]);


async function getTag() {
  const response = await TagCenter.getTags();
  tags.value = [
    '全部',
    ...response.data.data.map((tag: { name: string }) => tag.name)
  ];;
}


async function getArticle() {
  const response = await articleStor.getArticle();
  articles.value = response.data.data;
}

onMounted(() => {
  getTag();
  getArticle();
});


const filteredArticles = computed(() => {
  return articles.value.filter(item => {
    const matchesTag = activeTag.value === '全部' || 
                      (item.tags && item.tags.includes(activeTag.value));
    const matchesSearch = item.title.toLowerCase().includes(search.value.toLowerCase());
    return matchesTag && matchesSearch;
  });
});
const goToArticlePage = (id: number) => {
  router.push({ name: 'essayHome', params: { id } });
};
</script>

<style scoped>
.input_home {
  background-image: url(https://img-s.msn.cn/tenant/amp/entityid/BB1msKSm?w=0&h=0&q=60&m=6&f=jpg&u=t);
  width: 100%;
  padding: 20px;
}

.input_home input {
  width: 300px;
  height: 30px;
  padding: 8px;
  margin-left: 400px;
  font-size: 16px;
  border: 1px solid #ddd;
}


.tag-group {
  margin: 15px 0;
  display: flex;
  flex-wrap: wrap;
}

.article-card {
  margin-bottom: 20px;
}

.card-header {
  padding: 10px 0;
}

.article-content {
  margin: 10px 0;
  color: #666;
  line-height: 1.6;
}

.article-meta {
  margin-top: 15px;
  font-size: 12px;
}
</style>
